<template>
  <page-wrap stay-still back hide-tab bgColor="#fff" contentWrapColor="#fff">
    <view class="bigTitle"> 选择简历模板 </view>
    <view class="smallTitle"> 填写在线简历，更快的生成专属你的简历 </view>
    <view class="template-box">
      <u-row gutter="24" justify="space-around">
        <u-col span="6" v-for="item in templateList" :key="item.temId">
          <view @click="previewTemplate(item)">
            <image :src="item.temPic" class="img"></image>
            <view class="temName">{{ item.temName }}</view>
          </view>
        </u-col>
      </u-row>
      <u-popup v-model="show" mode="bottom" height="100vh" closeable>
        <view class="preview">
          <view class="img-box">
            <u-image
              :src="currentTemplate.temPic"
              mode="widthFix"
              width="90vw"
            ></u-image>
          </view>
          <view class="produce-btn">
            <view class="btn" @click="selectTemplate">选择此模板</view>
          </view>
        </view>
      </u-popup>
      <u-popup v-model="showWish" mode="bottom" height="90vh" closeable>
        <view class="preview">
          <view class="wishContent">
            <view class="title">选择期望职位</view>
            <view class="temName" v-if="allAimList.length != 0"
              >任意选择一个职位，生成专属你的简历</view
            >
            <view
              class="card"
              v-for="(item, index) in allAimList"
              :key="index"
              @click="chooseWish(item)"
            >
              <view class="cardLeft">
                <view class="cardLeft_title"
                  >{{ item.cityName ? '[' + item.cityName + ']' : ''
                  }}{{ item.zwname }}</view
                >
                <view class="cardLeft_money"
                  >{{ item.salary_str }} | {{ item.tradeName }}</view
                >
              </view>
              <view class="cardRight">
                <image
                  class="delete-icon"
                  :src="deleteResume"
                  @click.stop="handleDelete(item)"
                ></image>
                <image
                  class="right-arrow"
                  :src="rightArrow"
                  @click.stop="handleEditWantJob(item)"
                ></image>
              </view>
            </view>
            <view class="empty">
              <view class="no-data" v-if="!allAimList.length">
                <image :src="noData" class="no-data-img"></image>
                <text class="text"
                  >暂无求职意向，请点击下方按钮新增求职意向</text
                >
              </view>
            </view>
            <view class="footer">
              <view :class="['btn']" @click="handleAddWantJob"
                >新增求职意向</view
              >
            </view>
          </view>
        </view>
      </u-popup>
    </view>
    <view @click="toNewResumeIndex" class="rightFixedButton up"
      >编辑在线简历</view
    >
    <view type="primary" @click="toEnclosure" class="rightFixedButton"
      >上传附件简历一键生成</view
    >
    <LoginDialog
      ref="loginDialog"
      @loginSuccessBack="loginSuccessBack"
    ></LoginDialog>
  </page-wrap>
</template>

<script>
import ShareMixin from '@/mixins/share';
import { getMyIntendedTradeList, deleteIntendedTrade } from '@/api/index';
import {
  createResumeAttachment,
  getPersonResumeAttachment,
  getResumeTemplate,
} from '@/api/modules/resumeCreate';
import {
  getResumeData,
  addBuryingPoint,
  cardRegist,
  getUserInfo,
} from '@/api/modules/career';
import { env } from '@/api/root';
import LoginDialog from '@/components/LoginDialog';
export default {
  mixins: [ShareMixin],
  components: { LoginDialog },
  data() {
    return {
      deleteResume: this.$imgBase + 'resume/delete_resume.png',
      rightArrow: this.$imgBase + 'career/right-arrow.png',
      noData: this.$imgBaseSelf + 'resume/no_data_resume.png',
      personId: uni.getStorageSync('person-id').slice(2) || undefined,
      templateImg: this.$imgBase + 'resume/template.png',
      show: false,
      showWish: false,
      currentTemplate: {},
      templateList: [
        {
          temId: 1,
          temPic: this.$imgBase + 'resume/template2.png',
          temName: '深蓝通用简历',
        },
      ],
      personId: uni.getStorageSync('person-id').slice(2) || undefined,
      allAimList: [],
      timer: null,
      startTime: 0, // 初始开始请求时间

      sharePath: '/pagesSub/newResume/resumeTemplate/index',
      shareTitle: '增加HR对你的印象分，生成专属你的简历',
      imageUrl: '',
    };
  },
  onShow() {
    uni.$on('wantJobUpdate', () => {
      this.getMyIntendedTradeListFn();
    });
  },
  onUnload() {
    uni.$off('wantJobUpdate');
  },
  created() {},
  onLoad() {
    if (!this.personId) {
      this.showLoginDialog();
      return;
    }
    this.getMyIntendedTradeListFn();
    this.getTemPlateList();
    this.getResumeData();
    this.addBuryingPointFn(20018);
    this.imageUrl =
      'https://img3.job1001.com/ypMp/elan/images/resume/resumeTemplateShareImage.png';
  },
  methods: {
    handleEditWantJob(item) {
      uni.navigateTo({
        url: `/pagesSub/newResume/aimItem/index?intended_id=${item.intended_id}`,
      });
    },
    handleDelete(item) {
      if (this.allAimList.length <= 1) {
        uni.showToast({
          title: '至少保留一个求职意向',
          icon: 'none',
          duration: 1500,
        });
        return;
      }
      uni.showModal({
        title: '温馨提示',
        content: `确认删除求职意向？`,
        success: (res) => {
          if (res.confirm) {
            const data = {
              person_id: this.personId,
              intended_id: item.intended_id,
            };
            deleteIntendedTrade(data).then((res) => {
              if (res.code == 200) {
                this.getMyIntendedTradeListFn();
                uni.setStorageSync('resumeUpdated', true); //设置一个标识，在resumeAssesment如果为true才会请求接口
                uni.showToast({
                  icon: 'none',
                  title: '删除成功',
                });
              } else {
                uni.showToast({ icon: 'none', title: res.status_desc });
              }
            });
          }
        },
      });
    },
    //普通的埋点
    async addBuryingPointFn(etId) {
      if (!this.personId) return;
      const params = {
        etId: etId,
        personId: uni.getStorageSync('person-id').slice(2) || '',
        cardType: this.cardType
          ? this.cardType
          : uni.getStorageSync('cardType') || this.cardType,
        consultantId: uni.getStorageSync('sellId')
          ? uni.getStorageSync('sellId')
          : '',
        // statType: this.statType ? this.statType : null,
        originType: this.originFrom == 'shareLink' ? 10 : 20,
      };
      const res = await addBuryingPoint(params);
    },
    getResumeData() {
      return new Promise((resolve, reject) => {
        let param = {
          personId: this.personId,
          conditionArr: JSON.stringify({
            is_mp: 1,
          }),
        };
        getResumeData(param)
          .then((res) => {
            //拿到后判断用户是否都填了必填项
            this.checkResumeCompleteness(res.data);
            resolve(true);
          })
          .catch((err) => {
            reject(false);
          });
      });
    },
    //检查简历完整性
    checkResumeCompleteness(resumeData) {
      //求职状态
      const jobStatusCompleteness = !!resumeData.person_status;
      //求职意向
      const myTendedCompleteness =
        resumeData.myTended && resumeData.myTended.length != 0;
      //工作经历
      const personWorkCompleteness =
        resumeData.personWorkArr && resumeData.personWorkArr.length != 0;
      //教育背景
      const personEdusCompleteness =
        resumeData.personEdusArr && resumeData.personEdusArr.length;

      this.isResumeComplete = !!(
        jobStatusCompleteness &&
        myTendedCompleteness &&
        personWorkCompleteness &&
        personEdusCompleteness
      );
    },
    toNewResumeIndex() {
      if (!this.personId) {
        this.showLoginDialog();
        return;
      }

      this.addBuryingPointFn(20021);
      uni.navigateTo({
        url: '/pagesSub/newResume/index',
      });
    },
    toEnclosure() {
      if (!this.personId) {
        this.showLoginDialog();
        return;
      }

      this.addBuryingPointFn(20020);
      uni.navigateTo({
        url: `/pagesSub/userCenter/enclosure/index`,
      });
    },
    async loginSuccessBack() {
      this.personId = uni.getStorageSync('person-id').slice(2) || undefined;
      this.getResumeData();
      this.getMyIntendedTradeListFn();
      this.getTemPlateList();
      await this.getUserInfoFn();
    },
    async cardRegistFn() {
      const params = {
        personId: this.personId,
      };
      if (env == 'test') {
        params.cardType = 54;
      } else if (env == 'pro') {
        params.cardType = 28;
      }
      const res = await cardRegist(params);
      return res;
    },
    async getUserInfoFn() {
      uni.showLoading({ title: '' });
      // 这个uid一定要传，因为在interceptors中，没有传参的请求的请求头不会带上uid，而这个请求一定要uid
      const res = await getUserInfo({ uid: '' });
      if (res.code == 200) {
        //如果没有cardType就绑定一个q2c端的
        if (res.data && !res.data.cardType) {
          const registerRes = await this.cardRegistFn();
          uni.hideLoading();
          if (registerRes.code !== 200) {
            uni.showToast({
              title: registerRes.status_desc,
              icon: 'none',
            });
          } else if (registerRes.code == 200) {
            const infoRes = await getUserInfo({ uid: '' });
            if (infoRes.code == 200) {
              uni.setStorageSync('personName', infoRes.data.personName);
              uni.setStorageSync('cardType', infoRes.data.cardType);
            }
          }
        } else {
          uni.setStorageSync('personName', res.data.personName);
          uni.setStorageSync('cardType', res.data.cardType);
        }
      }
    },
    showLoginDialog() {
      this.$refs.loginDialog.setVisibility(true);
    },
    getTemPlateList() {
      const params = {
        personId: this.personId,
      };
      getResumeTemplate(params)
        .then((res) => {
          if (res.code == 200) {
            this.templateList = res.data;
          }
        })
        .catch((e) => {
          console.log(e);
        });
    },
    chooseWish(item) {
      uni.showLoading({
        title: '加载中',
        mask: true,
      });

      let param = {
        personId: this.personId,
        temId: this.currentTemplate.temId,
        attName: '一览简历',
        attType: '1',
        attStatus: '2',
        intendedId: item.intended_id,
        intendName: item.zwname,
        salary: item.salary_str,
      };
      uni.setStorageSync('resumeTempalteSelectIntend', item);
      // return;
      createResumeAttachment(param).then((res) => {
        if (+res.code === 200 && res.data.presentResumeNum < 3) {
          uni.hideLoading();
          uni.showToast({ icon: 'none', title: '简历提交成功' });
          uni.showLoading({
            title: '简历拼命生成中~',
            mask: true,
          });
          this.startTime = new Date().getTime();
          this.getResumeTime();
        } else if (res.data && res.data.presentResumeNum >= 3) {
          uni.showToast({ icon: 'none', title: '简历附件数量超过限制' });
        } else {
          uni.showToast({ icon: 'none', title: res.status_temName });
        }
      });
    },
    getResumeTime() {
      clearTimeout(this.timer); // 清除定时器
      // 超过30分钟则停止轮询
      console.log(
        'new Date().getTime() - this.startTime > 30 * 1000',
        new Date().getTime() - this.startTime,
        30 * 1000 * 60
      );

      if (new Date().getTime() - this.startTime > 30 * 1000 * 60) {
        clearTimeout(this.timer);
        uni.showToast({ icon: 'none', title: '服务器繁忙，请稍后重试' });
        return;
      }
      // 3s一次, 轮询中
      this.timer = setTimeout(() => {
        this.getResume(); // 调用轮询
      }, 2000);
    },
    getResume() {
      let param = {
        personId: this.personId,
        temId: this.currentTemplate.temId,
      };
      getPersonResumeAttachment(param)
        .then((res) => {
          if (res && res.data.attUrl) {
            console.log('成功了');
            uni.hideLoading();
            clearTimeout(this.timer);
            uni.navigateTo({
              url: `/pagesSub/resume/resumeTemplate/resumeDetail/index?id=${
                res.data.id
              }&attPic=${encodeURIComponent(res.data.attPic)}`,
            });
          } else {
            // uni.hideLoading();
            // clearTimeout(this.timer);
            // uni.navigateTo({
            //   url: `/pagesSub/resume/resumeTemplate/resumeDetail/index?id=${res.data.id}&attUrl=${res.data.attUrl}`,
            // });
            // 没成功,调用轮询
            this.getResumeTime();
          }
        })
        .catch((err) => {
          // 请求错误,也继续轮询
          this.getResumeTime();
        });
    },
    selectTemplate() {
      this.show = false;
      this.showWish = true;
    },
    getMyIntendedTradeListFn() {
      let param = {
        person_id: this.personId,
      };
      getMyIntendedTradeList(param).then((res) => {
        if (+res.code === 200) {
          this.allAimList = res.data.myTended || [];
        }
      });
    },
    handleAddWantJob() {
      if (this.allAimList.length >= 3) {
        uni.showToast({
          title: '最多只能添加三个求职意向',
          icon: 'none',
          duration: 1500,
        });
        return;
      }
      uni.navigateTo({ url: '/pagesSub/newResume/aimItem/index' });
    },
    previewTemplate(item) {
      if (!this.personId) {
        this.showLoginDialog();
        return;
      }
      this.currentTemplate = item;
      this.showWish = true;
    },
  },
};
</script>

<style lang="scss" scoped>
.bigTitle {
  padding-top: 46rpx;
  font-size: 40rpx;
  background-color: white;
  padding-left: 36rpx;
  font-weight: bold;
  letter-spacing: 2rpx;
  margin-bottom: 4rpx;
}
.smallTitle {
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;
  font-size: 28rpx;
  padding-left: 36rpx;
  color: #999999;
  line-height: 40rpx;
  text-align: left;
  font-style: normal;
  margin-bottom: 8rpx;
}
.template-box {
  padding: 32rpx 24rpx;
  background-color: white;
  // min-height: 100vh;
  .img {
    width: 330rpx;
    height: 468rpx;
    box-shadow: 0rpx 4rpx 20rpx 4rpx rgba(212, 217, 238, 0.5);
    border-radius: 16rpx;
    background: #d8d8d8;
    margin-bottom: 16rpx;
  }
  .temName {
    text-align: center;
    word-break: break-all;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2; /* 这里是超出几行省略 */
    overflow: hidden;
    margin-bottom: 24rpx;
    font-family: PingFangSC, PingFang SC;
    font-weight: 400;
    font-size: 28rpx;
    color: #555555;
    line-height: 40rpx;
    text-align: center;
    font-style: normal;
  }
}
.preview {
  position: relative;
  .img-box {
    text-align: center;
  }
  .produce-btn {
    width: 100%;
    display: flex;
    justify-content: center;
    padding: 0 32rpx;
    position: fixed;
    bottom: 0rpx;
    padding-bottom: calc(2rpx + constant(safe-area-inset-bottom));
    padding-bottom: calc(2rpx + env(safe-area-inset-bottom));
    .btn {
      width: 100%;
      background: #f75a3e;
      color: #fff;
      font-size: 14px;
      height: 80rpx;
      line-height: 80rpx;
      margin-bottom: 20rpx;
    }
  }
  .wishContent {
    padding: 32rpx;
    min-height: 880rpx;
    position: relative;
    .title {
      font-weight: 800;
      font-size: 40rpx;
      color: #000000;
      line-height: 56rpx;
    }
    .temName {
      font-weight: 400;
      font-size: 26rpx;
      color: #555555;
      line-height: 36rpx;
      text-align: left;
      font-style: normal;
      margin-top: 18rpx;
      margin-bottom: 36rpx;
    }
    .card {
      margin-bottom: 24rpx;
      border-radius: 10rpx;
      display: flex;
      // height: 200rpx;
      padding: 32rpx;
      background: #f5f6f7;
      .cardRight {
        display: flex;
        align-items: center;
        .delete-icon {
          width: 60rpx;
          height: 60rpx;
        }
        .right-arrow {
          width: 32rpx;
          height: 32rpx;
          padding: 26rpx 26rpx 26rpx 14rpx;
        }
      }
      .cardLeft {
        flex: 1;
        display: flex;
        flex-direction: column;
        justify-content: space-around;
        .cardLeft_title {
          font-size: 16px;
          font-weight: 900;
          margin-bottom: 20rpx;
        }
        .cardLeft_money {
          font-size: 14px;
          color: #5f5d5d;
        }
        .cardLeft_type {
          font-size: 12px;
          color: #888;
        }
      }
    }
  }
}
.empty {
  .no-data {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    .no-data-img {
      width: 360rpx;
      height: 360rpx;
      margin-bottom: 24rpx;
    }
    .text {
      font-size: 28rpx;
      color: #888888;
      line-height: 40rpx;
    }
  }
}
.footer {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  position: absolute;
  bottom: 65rpx;
  left: 0;
  .btn {
    height: 80rpx;
    line-height: 80rpx;
    width: calc(100% - 64rpx);
    border-radius: 12rpx;
    background: #f75a3e;
    color: #fff;
    text-align: center;
  }
}
::v-deep .u-image__image {
  margin: 80rpx 40rpx 120rpx 40rpx;
}
.rightFixedButton {
  position: fixed;
  bottom: 328rpx;
  right: 0rpx;
  display: flex;
  align-items: center;
  // width: 240rpx;
  height: 76rpx;
  padding: 10rpx 19rpx;
  background: #ffffff;
  box-shadow: 0rpx 2rpx 18rpx 0rpx rgba(0, 0, 0, 0.15);
  border-radius: 200rpx 0rpx 0rpx 200rpx;
  font-family: PingFang-SC, PingFang-SC;
  font-weight: bold;
  font-size: 26rpx;
  color: #555555;
  line-height: 34rpx;
  text-align: left;
  font-style: normal;
  z-index: 200;

  &.up {
    bottom: 228rpx;
  }
}
</style>
